<?php
/*
 * 用户管理
 *
 *
 */
class UserMgrAction {

	private $_error_msg = '';
	private $_observer  = NULL;
	private $_is_register_with_mobile;
	private $_current_register_user_info;

	public function __construct ()
	{
		$this->_cache = Cache::instance();
	}

	/*
	 * 注册搜狐PASSPORT用户账户
	 *
	 * @param	array	info = array('userid', 'password', 'uniqname', 'email')
	 * @return	boolean
	 */
	public function createSohuPassport ($info) 
	{
		if (empty($info) || empty($info['userid']))
			throw new Exception("参数错误!");
	
		$sohuPassportApi = new ComSohuPassportApi();
		$response = $sohuPassportApi->createUser($info); 
		
		if (empty($response) || !isset($response['status']))
			throw new SCException("创建搜狐通行证账户失败，请重试");

		if ($response['status'] == 4) 
	        throw new SCException("创建搜狐通行证账号失败, 用户<{$info['userid']}>已经存在");
		else if ($response['status'] != 0) 
	        throw new SCException("创建搜狐通行证账号失败, 请重试");

		return TRUE;
	}

	public function isRegisterWithMobile ()
	{
		return $this->_is_register_with_mobile;
	}

	public function getCurrentRegisterUserId ()
	{
		if (!empty($this->_current_register_user_info))
			return $this->_current_register_user_info['id'];
		else
			return 0;
	}

	/*
	 * 创建激活状态的爱家团账户(并激活相应的搜狐PASSPORT账户)
	 * 并记录其手机号码
	 *
	 */
	public function createActiveUserWithMobileByPassport($passport, $passport_info = array(), $mobile = NULL)
	{
		$this->_is_register_with_mobile = FALSE;
		$this->_current_register_user_info = NULL;

		$this->createUserByPassport($passport, $passport_info, TRUE);

		$this->_is_register_with_mobile = TRUE;

		// 更新手机号码
		$user = new Model_User();
		$user_info = $user->getUserInfoByPassport($passport);
		if (!empty($user_info))
		{
			$this->_current_register_user_info = $user_info;
			$uid = $user_info['id'];
			$user->updateUserInfo(
					array('id' => $uid),
					array('mobile' => $mobile)
					);
		}

		// notify
		$this->notify();
	}

	/*
	 * 创建激活状态的账户(并激活相应的搜狐PASSPORT账户)
	 *
	 */
	public function syncActiveUserByPassport($passport, $passport_info = array())
	{
		$this->createUserByPassport($passport, $passport_info, TRUE, TRUE);
	}

	/*
	 * 创建激活状态的账户(并激活相应的搜狐PASSPORT账户)
	 *
	 */
	public function createActiveUserByPassport($passport, $passport_info = array())
	{
		$this->createUserByPassport($passport, $passport_info, TRUE);
	}

	/*
	 * 创建未激活状态的账户(不激活相应的搜狐PASSPORT账户)
	 *
	 */
	public function createInactiveUserByPassport($passport, $passport_info = array())
	{
		$this->createUserByPassport($passport, $passport_info, FALSE);
	}

	/*
	 * 使用搜狐PASSPORT, 创建爱家团用户
	 *
	 * @uses	ComSohuPassportApi, UserAction
	 * @param	string		passport账户(电子邮件地址)
	 * @param	array		爱家团用户信息 (optional)
	 * @param	boolean		是否激活搜狐Passport账户 (optional)
	 * @return	boolean
	 */
	protected function createUserByPassport ($passport, $passport_info = array(), 
					$activate_passport = FALSE, $ignore_activate = FALSE) 
	{
		$status = 0;
		$this->ipLimit();

		if (empty($passport))
			throw new Exception("Passport 账户不能为空");

		$sohuPassportApi = new ComSohuPassportApi();

		if ($activate_passport)
		{
			$status |= Kohana::config('user.status.activated');

			// 搜狐域邮件账户激活(免激活)
			if (! Util::isSohuDomainEmail($passport) && ! $ignore_activate)
			{
				// 激活用户的搜狐Passport
				$response = $sohuPassportApi->activateUser($passport); 
				if (! isset($response['status']) || $response['status'] != 0) 
					throw new Exception("通行证账户<{$passport}>激活失败");
			}
		}
	
		if(preg_match('/^.+@focus\.cn$/i', $passport))
		{
			$pInfo = array('userid'=>$passport, 'status'=>0, 'nickname'=>'');
		}
		else
		{
			$pInfo = $sohuPassportApi->getUserInfo($passport);
			if (empty($pInfo) || !is_array($pInfo) || $pInfo['status'] != 0 || empty($pInfo['userid']))
				throw new Exception("无法获取搜狐通行证的信息");
		}

			//if ($activate_passport && empty($pInfo['question']))
		//	throw new Exception("搜狐通行证参数非法,拒绝注册");

		$mobile     = '';
		$mobileInfo = $sohuPassportApi->wapGetMobile($passport);
		$nickname   = isset($passport_info['nickname']) && !empty ($passport_info['nickname']) ? 
							$passport_info['nickname'] : 
							$pInfo['nickname'];

		// 判断当前用户的手机状态
		if (!empty($mobileInfo) && is_array($mobileInfo) && isset($mobileInfo['status'])) 
		{
			if (isset($mobileInfo['mobile']) && $mobileInfo['status'] == 0)
			{
				$status |= Kohana::config('user.status.mobile_binded');
				$mobile  = $mobileInfo['mobile'];
			}
		}

		// 创建账户
		//////////////////////////////////////////////////////////
		$info = array(
			'passport'  => $pInfo['userid'], 
			'nickname'  => $nickname, 
			'mobile'    => $mobile, 
			'status'    => $status,
		);

		if (empty($info['nickname']))
			$info['nickname'] = Util::build_nickname($info['passport']);
		
		// 创建装修网会员
		$uid = user::create($info, $status);

		// 创建会员失败
		if (empty($uid))
			throw new Exception("搜狐通行证账户: <{$passport}>创建成功，注册失败");
		// 记录用户注册来源
		//$user->setRegisterSource($uid);

		// 设置用户再次登录时的提示语（提示使用邮件地址登录)
		//$user->setPassportRegCookie();
	
		return TRUE;
	}


	/*
	 * 激活搜狐Passport的用户
	 *
	 *
	 */
	public function activateSohuPassportAccount ($passport)
	{
		$sohuPassportApi = new ComSohuPassportApi();
		$email = strtolower(trim($passport));

		if (! FSUtility::isEmail($email))
			return FALSE;

		// 搜狐域邮件账户激活(免激活)
		if (Util::isSohuDomainEmail($email))
		{
			return TRUE;
		}
		else
		// 外域邮件账户激活
		{
			$response = $sohuPassportApi->activateUser($email); 
			if (isset($response['status']) AND $response['status'] == 0) 
				return TRUE;
			else 
				return FALSE;
		}
	}

	/*
	 * 根据passport返回Sohu Passport Uid  (passport的uid，不是爱家团的uid)
	 */
	public function passport2passportid ($passport)
	{
		$sohuPassportApi = new ComSohuPassportApi();
		return $sohuPassportApi->getUidByPassport($passport);
	}

	/*
	 * 同步搜狐Passport下的用户信息到搜狐爱家团用户账户
	 *		同步的类容包括：昵称，姓名，手机是否绑定
	 *
	 * @param	string	email
	 * @return	boolean	
	 */
	protected function syncSohuPassportInfo ($email)
	{
		$sohuPassportApi = new ComSohuPassportApi();
		$userAction      = Model::factory('user');

		$pInfo = $sohuPassportApi->getUserInfo($email);
		$mobileInfo = $sohuPassportApi->wapGetMobile($email);
		$mobileflag = 1;	// 没有绑定手机
	
		// 注册ihome用户
		// 调用焦点接口创建爱家会员
		//////////////////////////////////////////////////////////////

		// 判断当前用户的手机状态
		if (!empty($mobileInfo) 
				&& is_array($mobileInfo) 
				&& isset($mobileInfo['status'])) 
		{
			if ($mobileInfo['status'] == 0)
			{
				if (isset($mobileInfo['mobile']) && !empty($mobileInfo['mobile']))
					$mobileflag = 4;	// 已经绑定
			}
		}
	
		$info = array(
			'email'     => $pInfo['email'],
			'password'  => NULL,
			'realname'  => utf8::substr($pInfo['nickname'], 0, 7),
			'nickname'  => utf8::substr($pInfo['nickname'], 0, 7),
			'mobile'    => $pInfo['mobile'],
			'mobileflag'=> $mobileflag,	// 当前手机状态 
		);
	
		// 检查昵称和用户真实姓名(有时Passport里面的用户信息并不完整)
		if (empty($info['realname']))
			$info['realname'] = Util::build_nickname($email);
	
		if (empty($info['nickname']))
			$info['nickname'] = Util::build_nickname($email);
		
		if (! $userAction->updateUserInfo(array('login_name' => $pInfo['userid']), $info)) {
			// 更新ihome会员信息失败
			header("Location: /");
			exit(0);
		}

		return TRUE;
	}

	protected function notify ()
	{
		if (empty($this->_observer))
			$this->_observer = new RegisterObserver();
		$this->_observer->update($this);
	}

	protected function ipLimit ()
	{
		$ip = FSUtility::getUserIP();
		$ip_int = ip2long($ip);
		$key = "reg_limit_{$ip_int}";

		$times = 0;
		$value = $this->_cache->Get($key);
		if (! empty($value))
		{
			$last_ip   = $value[0];
			$times     = $value[1];

			/*
			if ( $ip == $last_ip  &&
				 $times >= 10)
				throw new Exception ("手累了吧？请歇会吧");
			*/

		}

		$this->_cache->Set($key, array($ip, ++$times), 7200); 
	}
}
